﻿#include "basenetworkaccessmanager.h"
#include <QDebug>

const static QString STATUS_SUCCESS = "success";
BaseNetworkAccessManager::BaseNetworkAccessManager(QObject *parent) : QNetworkAccessManager(parent)
{
    connect(this, &QNetworkAccessManager::finished,
            [=]()
    {
        QVariant status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

        if(status.toInt() != 200){
            emit onFailed("网络连接失败！");
            return ;
        }

        QByteArray bytes = reply->readAll();
        QString res(bytes);
        QJsonParseError jsonError;
        QJsonDocument document = QJsonDocument::fromJson(bytes, &jsonError);
        QJsonObject object = document.object();
        QString state = object.value("status").toString();
        QString message = object.value("message").toString();
        if(state == "success"){
            if(object.contains("data")){
                QJsonObject dataObject = object.value("data").toObject();
                emit onSuccessWithData(message, dataObject);
            }else{
                emit onSuccess(message);
            }
        }else {
            emit onFailed(message);
        }
    });
}

void BaseNetworkAccessManager::doGet(const QString url)
{
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/json");
    request.setUrl(QUrl(url));
    reply = this->get(request);
}

void BaseNetworkAccessManager::doPost(const QString url, const QByteArray data)
{
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    reply = this->post(request, data);
}
